package com.dao.c.backend.service.impl;

import com.dao.c.backend.common.CommonResult;
import com.dao.c.backend.common.MessageCode;
import com.dao.c.backend.common.StatusCode;
import com.dao.c.backend.dao.ModelMapper;
import com.dao.c.backend.entity.Category;
import com.dao.c.backend.dao.CategoryMapper;
import com.dao.c.backend.entity.Model;
import com.dao.c.backend.service.ICategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张幸晔
 * @since 2025-06-04
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ModelMapper modelMapper;
    @Override
    public CommonResult listTree() {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getStatus, StatusCode.DATA_EXIST);
        LambdaQueryWrapper<Model> modelLambdaQueryWrapper = new LambdaQueryWrapper<>();

        modelLambdaQueryWrapper.eq(Model::getStatus, StatusCode.DATA_EXIST)
                .select(Model.class, i -> !i.getColumn().equals("url") && !i.getColumn().equals("api") && !i.getColumn().equals("status"));
        //两次数据库查找，找出所有分类与模型
        List<Category> categories = categoryMapper.selectList(categoryLambdaQueryWrapper);
        List<Model> models = modelMapper.selectList(modelLambdaQueryWrapper);
        //查询都为空则直接返回查询失败
        if (categories.size() == 0 || models.size() == 0){
            return new CommonResult<>(StatusCode.ERROR, MessageCode.SELECTFAIL,null);
        }
        Map<Integer,List<Model>> modelsGroupByCategoryId = models.stream().collect(Collectors.groupingBy(Model::getCategoryId));
        //开始构建树：并找出所有第一级菜单
        List<Category> categoryTree = categories.stream()
                .filter(category -> category.getCategoryLevel() == 1)//过滤出第一级
                .map(rootCategory ->{
                    //为每一级菜单递归设置子节点
                    setChildren(rootCategory,categories,modelsGroupByCategoryId);
                    return rootCategory;
                }).collect(Collectors.toList());
        return new CommonResult<>(StatusCode.SUCCESS, MessageCode.SELECT,categoryTree);
    }


    @Override
    public CommonResult listAll() {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getStatus, StatusCode.DATA_EXIST);
        return new CommonResult(StatusCode.SUCCESS, MessageCode.SELECT, categoryMapper.selectList(categoryLambdaQueryWrapper));
    }

    private void setChildren(Category parentCategory, List<Category> categories, Map<Integer, List<Model>> modelsGroupByCategoryId) {
        parentCategory.setChildren(new ArrayList<>());
        //查找出所有子菜单（即路径匹配的下一级菜单）
        List<Category> childrenCategories = categories.stream()
                .filter(category -> category.getCategoryLevel() == parentCategory.getCategoryLevel()+1)
                //查找出带有父亲分类的路径前缀的子菜单
                .filter(category -> category.getCategoryUrl() != null && category.getCategoryUrl().startsWith(parentCategory.getCategoryUrl()))
                .collect(Collectors.toList());

        for (Category childrenCategory : childrenCategories){
            parentCategory.getChildren().add(childrenCategory);
            //递归设置每一级子分类
            setChildren(childrenCategory,categories,modelsGroupByCategoryId);
        }
        //如果是二级分类，则将相关模型放入放入其子菜单
        if (parentCategory.getCategoryLevel() == 2){
            List<Model> relatedModels = modelsGroupByCategoryId.getOrDefault(parentCategory.getId(), new ArrayList<>());
            parentCategory.getChildren().addAll(relatedModels);
        }
    }
}
